package cn.itcast.wanxinp2p.account.service;/*
 *   @author Dram
 *   @create 2021-04-28 10:55
 */

import cn.itcast.wanxinp2p.common.domain.BusinessException;
import cn.itcast.wanxinp2p.common.domain.CommonErrorCode;
import cn.itcast.wanxinp2p.common.domain.RestResponse;
import cn.itcast.wanxinp2p.common.util.OkHttpUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class SmsService {
    @Value("${sms.url}")
    private String SmsUrl;

    @Value("${sms.enable}")
    private Boolean enable;

    /**
     * 发送并获取短信验证码
     * @param mobile
     * @return
     */
    public RestResponse getSMSCode(String mobile) {
        if (enable){
           return OkHttpUtil.post(SmsUrl + "/generate?effectiveTime=300&name=sms", "{\"mobile\":" + mobile + "}");
        }
        return RestResponse.success();
    }

    /**
     * 校验短信验证码
     * @param key 校验标识
     * @param code 短信验证码
     */
    public void verifySmsCode(String key,String code){
        if (enable){

            StringBuilder sb = new StringBuilder();

            sb.append("/verify?name=sms&verificationKey=").append(key).append("&verificationCode=").append(code);
            RestResponse response = OkHttpUtil.post(SmsUrl + sb.toString(), "");
            Boolean result = (Boolean) response.getResult();
            if (response.getCode()!= CommonErrorCode.SUCCESS.getCode()){
                //不正常
                throw new BusinessException(CommonErrorCode.E_100102);
            }else if (!result){
                //不正常
                throw new BusinessException(CommonErrorCode.E_100102);
            }
        }
    }
}
